﻿using System;
using System.IO;
using System.Windows.Forms;

namespace ODM_Code.Forms
{
    public partial class AddAnalysisAreaForm : Form
    {
        public AddAnalysisAreaForm()
        {
            InitializeComponent();
        }

        private void addButton_Click(object sender, EventArgs e)
        {
            // Check user input
            if (newAreaNameBox.Text.Equals(""))
            {
                MessageBox.Show("You must enter a name for the new area.", "Invalid Name", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (newAreaPathBox.Text.Equals(""))
            {
                MessageBox.Show("You must enter a path for the new area.", "Invalid Path", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // Check if new path exists. If not, create it.
            string newPath = "C:\\magfire\\" + newAreaPathBox.Text;
            string inputPath = newPath + "\\input";
            string copyImportPath = newPath + "\\copyimport";
            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
                Directory.CreateDirectory(inputPath);
                Directory.CreateDirectory(copyImportPath);
                this.copyImport(copyImportPath);
            }
            else
            {
                //MessageBox.Show("That path already exists. Choose another.", "Invalid Path", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //return;
            }

            // Get current "extra" areas
            string extraAreas = ConfigSettings.ReadSetting("extraAreas");

            // Add new area name and path
            extraAreas += newAreaNameBox.Text + ":" + newAreaPathBox.Text + ";";

            ConfigSettings.WriteSetting("extraAreas", extraAreas);
            this.Close();
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void copyImport(string pathToCopyImport)
        {
            this.copyImport(null, pathToCopyImport);
        }

        private void copyImport(string pathToSourceFiles, string pathToCopyImport)
        {
            if (pathToSourceFiles == null)
            {
                pathToSourceFiles = "C:\\magfire\\masterlayers\\copyimport";
            }

            string[] filesToCopy = Directory.GetFiles(pathToSourceFiles);

            foreach (string sourceFile in filesToCopy)
            {
                int stringStartPos = sourceFile.LastIndexOf("\\");
                string destFile = pathToCopyImport + sourceFile.Substring(stringStartPos);
                File.Copy(sourceFile, destFile);
            }
        }

    }
}
